package com.nondo.rdp.finance.service.impl.course;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nondo.rdp.auth.common.DateUtils;
import com.nondo.rdp.auth.endpoint.model.Page;
import com.nondo.rdp.core.common.StatusConstant;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.repository.course.CourseRepository;
import com.nondo.rdp.finance.service.course.CourseService;

@Transactional
@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    CourseRepository courseRepository;

    @Override
    public Course findOne(Long id) {
        return this.courseRepository.findOne(id);
    }

    @Override
    public Course save(Course course) {
        return this.courseRepository.save(course);
    }

    @Override
    public void update(Course course) {
        this.courseRepository.save(course);
    }

    @Override
    public void delete(Long id) {
        this.courseRepository.deleteById(id);
    }

    @SuppressWarnings({ "rawtypes" })
	@Override
    public Page<Course> findAll(Page<Course> page, Course course) {
    	Sort sort = sort(course);//排序
    	
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Course> dictPage = courseRepository.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (course != null) {
                if (course.getType() != null) {
                    predicates.add(builder.equal(root.get("type"), course.getType()));
                }
                if (course.getRecommend() != null) {
                    predicates.add(builder.equal(root.get("recommend"), course.getRecommend()));
                }
                if (StringUtils.isNotEmpty(course.getName())) {
                    predicates.add(builder.like(root.get("name"), "%" + course.getName() + "%"));
                }
                if (course.getPclassifyId() != null && course.getPclassifyId() >0 ) {
                    predicates.add(builder.equal(root.get("pclassifyId"), course.getPclassifyId()));
                }
                if (course.getClassifyId() != null && course.getClassifyId() >0 ) {
                    predicates.add(builder.equal(root.get("classifyId"), course.getClassifyId()));
                }
                if (StringUtils.isNotEmpty(course.getSearchId())) {
                    List typeList = Arrays.asList(course.getSearchId().split(","));
                    predicates.add(root.get("id").in(typeList));
                }
            }
            predicates.add(builder.lessThanOrEqualTo(root.get("publishDate"), DateUtils.getNowTime()));
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            predicates.add(builder.equal(root.get("status"), StatusConstant.ON_SHELVE));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);

            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Course>(dictPage);
    }

	private Sort sort(Course course) {
		Sort sort = null;
		if(course == null){
			sort = new Sort(Sort.Direction.DESC, "createDate");
		}
    	if(StringUtils.isBlank(course.getSortNumSortDirection())&&StringUtils.isBlank(course.getReadNumSortDirection())){
    		sort = (new Sort(Sort.Direction.DESC, "sortNum")).and(new Sort(Sort.Direction.DESC, "publishDate"));
    	} else {
    		if(StringUtils.isNotBlank(course.getSortNumSortDirection())){
    			if ("ASC".equals((course.getSortNumSortDirection()))){
        			sort = (new Sort(Sort.Direction.ASC, "sortNum"));
        		}else if("DESC".equals((course.getSortNumSortDirection()))){
        			sort = (new Sort(Sort.Direction.DESC, "sortNum"));
        		}
    			if("ASC".equals((course.getReadNumSortDirection()))){
    				sort.and(new Sort(Sort.Direction.ASC, "readNum"));
    			}else if ("DESC".equals((course.getReadNumSortDirection()))) {
    				sort.and(new Sort(Sort.Direction.DESC, "readNum"));
    			}
    		} else {
				if("ASC".equals((course.getReadNumSortDirection()))){
					sort = new Sort(Sort.Direction.ASC, "readNum");
				}else if("DESC".contains((course.getReadNumSortDirection()))) {
					sort = new Sort(Sort.Direction.DESC, "readNum");
				}
    		}
			
    	}
		return sort;
	}

    @Override
    public Page<Course> findAllForAdmin(Page<Course> page, Course course) {
        Sort sort = new Sort(Sort.Direction.DESC, "sortNum").and(new Sort(Sort.Direction.DESC, "createDate"));
        PageRequest pageRequest = new PageRequest(page.getPageNumber(), page.getPageSize(), sort);
        org.springframework.data.domain.Page<Course> dictPage = courseRepository.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (course != null) {
                if (course.getId() != null) {
                    predicates.add(builder.equal(root.get("id"), course.getId()));
                }
                if (course.getType() != null) {
                    predicates.add(builder.equal(root.get("type"), course.getType()));
                }
                if (course.getHome() != null) {
                    predicates.add(builder.equal(root.get("home"), course.getHome()));
                }
                if (course.getRecommend() != null) {
                    predicates.add(builder.equal(root.get("recommend"), course.getRecommend()));
                }
                if (StringUtils.isNotEmpty(course.getName())) {
                    predicates.add(builder.like(root.get("name"), "%" + course.getName() + "%"));
                }
                if (course.getUser() != null) {
                    predicates.add(builder.equal(root.get("user").get("id"), course.getUser().getId()));
                }
                if (course.getPclassifyId() != null && course.getPclassifyId() >0 ) {
                    predicates.add(builder.equal(root.get("pclassifyId"), course.getPclassifyId()));
                }
                if (course.getClassifyId() != null && course.getClassifyId() >0 ) {
                    predicates.add(builder.equal(root.get("classifyId"), course.getClassifyId()));
                }
                if (course.getStatus() != null) {
                	predicates.add(builder.equal(root.get("status"), course.getStatus()));
                }
            }
            predicates.add(builder.like(root.get("delFlag"), StatusConstant.DEL_FLAG_NORMAL));
            Predicate[] predicatesArray = new Predicate[predicates.size()];
            predicates.toArray(predicatesArray);

            return builder.and(predicatesArray);

        }, pageRequest);

        return new Page<Course>(dictPage);
    }


    @Override
    public Course findByAlbumId(int albumId) {
        return this.courseRepository.findByAlbumId(albumId);
    }

    ;
}